package com.xqledu.admin.service.impl;

import com.xqledu.admin.dao.SysAccountMapper;
import com.xqledu.admin.dao.SysRoleMapper;
import com.xqledu.admin.dao.SysUserMapper;
import com.xqledu.admin.dao.UserRoleMapper;
import com.xqledu.admin.entry.enumeration.UserEnum;
import com.xqledu.admin.entry.pojo.SysAccount;
import com.xqledu.admin.entry.pojo.SysRole;
import com.xqledu.admin.entry.pojo.SysUser;
import com.xqledu.admin.entry.vo.SysUserDetails;
import com.xqledu.admin.entry.vo.UserInfo;
import com.xqledu.admin.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * @author 向其林
 * @version 1.0
 * @description: TODO
 * @date 2023/7/5 0005 22:35
 */
@Service
@Slf4j
public class SysUserServiceImpl implements SysUserService, UserDetailsService {
    @Resource
    private SysUserMapper userMapper;
    @Resource
    private SysAccountMapper accountMapper;
    @Resource
    private UserRoleMapper userRoleMapper;
    @Override
    public void saveTest() {
        SysUser sysUser = new SysUser();
        sysUser.setIsFlag(false);
        sysUser.setId("x232323sads");
        sysUser.setState("1");
        sysUser.setCreateTime(new Date());
        sysUser.setCreateBy("xql");
        userMapper.insert(sysUser);
    }
    @Override
    public void queryTest() {
        SysUser sysUser = userMapper.selectByPrimaryKey("x232323sads");
        System.out.println("sysUser = " + sysUser.getIsFlag());
    }

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        // 根据用户名查询用户信息
        SysAccount sysAccount = accountMapper.selectOneByOpenCode(s);
        // 如果查询不到数据或账号类型不符合要求，抛出异常
        Optional.of(sysAccount).orElseThrow(()->new UsernameNotFoundException("账号不存在"));

        SysUser user = userMapper.selectByPrimaryKey(sysAccount.getUserId());

        List<SysRole> sysRoles = userRoleMapper.selectRoleList(user.getId());
        UserEnum userEnum = UserEnum.fromCode(sysAccount.getOpenCode());
        // 构建 UserDetails 对象
        SysUserDetails userDetails = new SysUserDetails(new UserInfo(user, sysRoles), userEnum);

        return userDetails;
    }

}

